import router from '@/router'
// import Cookies from 'js-cookie'
import {Message} from 'element-ui';
import {getToken} from '@/util/auth';
import store from '@/store';

function hasPermission(roles,permissionRoles){
    if(roles=='admin')return true;
    if(!permissionRoles || JSON.stringify(permissionRoles)=="{}") return true
    if(permissionRoles.indexOf(roles)>=0) return true;
    return false
}

const whiteList=['/','404','403','/register']

// 全局路由前置守卫
router.beforeEach(async(to, from, next) => {
    // const userId=getToken();
    // if(!userId){
    //     await store.dispatch('account/resetToken')
    //     if(whiteList.indexOf(to.path)>=0){
    //         next()
    //         return
    //     }
    //     next('/')
    // }else{
    //     try{
    //         await store.dispatch('account/getUserInfo',{userId:userId})
    //         if(whiteList.indexOf(to.path)>=0){
    //             next();
    //             return
    //         }else{
    //             if(to.matched.length===0){
    //                 next({path:'/404',replace:true})
    //             }else{
    //                 if(hasPermission(store.state.account.roles,to.meta)){
    //                     next()
    //                 }else{
    //                     next({path:'/403',replace:true})
    //                 }
    //             }
    //         }
    //     }catch(error){
    //         await store.dispatch('account/resetToken');
    //         Message.error('用户信息异常，请尝试重新登录')
    //         next('/')
    //     }
    // }

    //获取令牌判断用户是否登录，拥有token
    if(whiteList.indexOf(to.path)>=0){
        next()
        return
    }else{
        if(!store.state.account.token){
            if(getToken()){
                store.commit('account/setToken', getToken())
            }else{
                Message.error('用户认证丢失')
                next('/')
            }
        }
        let tokenString=store.state.account.token;
        let getTokenInfo=JSON.parse(decodeURIComponent(escape(window.atob(tokenString.split('.')[1]))))
        console.log(getTokenInfo)
        try{
            //通过vuex action 异步获取用户信息
            await store.dispatch('account/getUserInfo', {userId:getTokenInfo.userid})
            console.log(store.state.account.user)
            next()
        }catch(error){
            await store.dispatch('account/resetToken')
            Message.error('用户信息异常，请尝试重新登录')
            next('/')
        }
    }
});
